-module(ap_80211_server).
-include("protocol.hrl").
-hehaviour(gen_server).
-define(SERVER,?MODULE).
-export([start/0,start_link/0,start_link/2,init/1,handle_call/3,handle_cast/2,handle_info/2,terminate/2,code_change/3]).
-export([handle/2,do/2]).
-record(ap_info,{
	ip = <<"0,0,0,0">>,
	ac_ip = <<"0.0.0.0">>,
	up_packet = 0,
	down_packet = 0,
	user_num = 0
}).


handle(Pid,Request) ->
	gen_server:cast(Pid,Request).
do(Pid,report)->
	io:format("dump counter ~p~n",[gen_server:call(Pid,report)]).
start()  ->
	gen_server:start({local, ?SERVER}, ?MODULE, [], []).
start_link(AP_ip,AC_ip) ->
	gen_server:start_link(?MODULE, [AP_ip,AC_ip], []).
	
start_link() ->
	start_link(undefined,undefined).
	
init([AP_ip,AC_ip]) ->
	error_logger:info_msg("ap server ~w start...",[AP_ip]),
	process_flag(trap_exit, true),
	{ok,{running,#ap_info{ip=AP_ip,ac_ip=AC_ip}}}.
	
handle_call(report,_,{running,IP,Counter}) ->
	{reply,{IP,Counter},{running,IP,Counter}};	
handle_call(Cmd,_,State) ->
	{reply, {error,io_lib:format("no func ~w define in ~s ~n",[Cmd,?MODULE])}, State}.
handle_cast(_, State) ->
	{noreply,State}.
handle_info(_, State) ->
	{noreply,State}.
terminate(_, _) ->
	ok.
code_change(_, State, _) ->
	{ok,State}.	
	
parse80211frame(Packet) ->
	<<I80211_Header:32/binary,Payload/binary>> = Packet,
	case I80211_Header of
	<<_SubType:4,2:2,_Ver:2,_OFlags:6,1:2,_Duration:16,BSSID:6/binary,S_MAC:6/binary,D_MAC:6/binary,_Other/binary>> -> %% data frame to STA
		{D_MAC,#sub_packet{dir=down,prot=llc,packet=Payload}};
	<<_SubType:4,2:2,_Ver:2,_OFlags:6,2:2,_Duration:16,D_MAC:6/binary,BSSID:6/binary,S_MAC:6/binary,_Other/binary>> -> %% data frame to DS
		{S_MAC,#sub_packet{dir=up,prot=llc,packet=Payload}};
	<<SubType:4,0:2,_Ver:2,_OFlags:6,Dir:2,_Duration:16,D_MAC:6/binary,S_MAC:6/binary,BSSID:6/binary,_Other/binary>> -> %%
		case i80211mgt_analysis(SubType,Dir) of
		up ->
			{S_MAC,#sub_packet{dir=up,prot=i80211mgt,packet=Packet}};
		down ->
			{D_MAC,#sub_packet{dir=down,prot=i80211mgt,packet=Packet}};
		unknown ->
			{unknown,#sub_packet{dir=unknow,prot=i80211mgt,packet=Packet}} %% ignore
		end;
	_ ->
		{unknown,#sub_packet{dir=unknow,prot=unknow,packet=Packet}}
	end.

i80211mgt_analysis(SubType,Dir) ->
	unknown.

		
		
		
		